package com.netty.cn.model.http.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;

/**
 * 
 * @author wangzonghui
 * @date 2021-11-02 14:56:52
 * @Description handler 定义
 */
public class JsoncatHandler extends SimpleChannelInboundHandler<FullHttpRequest>{
	
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	
	private final String FAVICON_ICO = "/favicon.ico";
    private final AsciiString CONNECTION = AsciiString.cached("Connection");
    private final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive");
    private final AsciiString CONTENT_TYPE = AsciiString.cached("Content-Type");
    private final AsciiString CONTENT_LENGTH = AsciiString.cached("Content-Length");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
    	String uri = fullHttpRequest.uri();
        log.info("请求地址：{}  类型：{}",fullHttpRequest.uri(),fullHttpRequest.method());
        if (uri.equals(FAVICON_ICO)) {
            return;
        }
        
        String result="GET请求";
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(result, CharsetUtil.UTF_8));
        
        response.headers().set(CONTENT_TYPE, "application/json");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
        
        boolean keepAlive = HttpUtil.isKeepAlive(fullHttpRequest);
        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
        	response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
    	log.info("连接地址：{}",ctx.channel().remoteAddress());
        ctx.flush();
    }

}
